package com.niit.activity.mapper;

import com.niit.activity.entity.Activity;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ActivityMapper {
    @Insert({"<script>",
            "INSERT INTO tb_activity (user_id, content, media_urls, visibility, likes_count, create_date, update_date, is_deleted, version, comment_num, topic_id)",
            "VALUES (#{userId}, #{content}, #{mediaUrls}, #{visibility}, #{likesCount}, #{createDate}, #{updateDate}, #{isDeleted}, #{version}, 0, #{topicId})",
            "</script>"})
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertActivity(Activity activity);

    //查询状态公开且未删除的动态
    @Select("SELECT * FROM tb_activity WHERE visibility = 0 AND is_deleted = 0")
    List<Activity> findPublicActivity();

    //删除动态
    @Update({"<script>",
        "UPDATE tb_activity SET is_deleted = 1, version = version + 1 WHERE id = #{id}",
        "</script>"})
    void markAsDeleted(@Param("id") Long id);

    //更改动态
    @Update({
            "<script>",
            "UPDATE tb_activity",
            "SET content = #{content}, media_urls = #{mediaUrls}, visibility = #{visibility}, topic_id = #{topicId},",
            "update_date = NOW(), version = version + 1",
            "WHERE id = #{id} ",
            "</script>"
    })
    int updateActivity(Activity activity);

    //点赞增加
    @Update("UPDATE tb_activity SET likes_count = likes_count + 1 WHERE id = #{id}")
    void incrementLikeCount(@Param("id") Long id);

    //取消点赞减少
    @Update("UPDATE tb_activity SET likes_count = GREATEST(0, likes_count - 1) WHERE id = #{id}")
    void decrementLikeCount(@Param("id") Long id);

    @Select("SELECT * FROM tb_activity WHERE id = #{id}")
    Activity getActivityById(Long id);

    @Select("SELECT * FROM tb_activity WHERE user_id = #{userId} AND is_deleted = 0")
    List<Activity> selectByUserId(@Param("userId") Long userId);
}